#include "Plane3D.h"
#include <limits>

namespace RayTracer
{
    Plane3D::Plane3D(Vector3D position, Vector3D normal) : Surface(position, normal)
    {
		Vector3D::Normalize(&normal);
    }
		
    HitInfo Plane3D::Hit (const Ray3D *ray, float tMin, float tMax) const
    {
		Vector3D hitPoint;

		Vector3D diff = Vector3D::Subtract(&this->position, &ray->position);

		float dot = DOT(diff, this->direction);
		float dot2 = DOT(ray->direction, this->direction);

		if(dot2 == 0.0f)
		{
			return HitInfo((ISurface*)this, &hitPoint, 0, HitInfo::Miss); // The ray is parallel to the plane, no intersection.
		}

		float d = dot / dot2;

		if(d < tMin || d > tMax)
		{
			return HitInfo((ISurface*)this, &hitPoint, d, HitInfo::Miss); // The Ray intersects the plane at or behind the eye.
		}

		hitPoint = Vector3D::Add(&ray->position, &Vector3D::MultiplyN(&ray->direction, d));
		return HitInfo((ISurface*)this, &hitPoint, d, HitInfo::Hit);
    }
		
    Vector3D Plane3D::Normal (const Vector3D *point) const
    {
	return this->direction;
    }
};
